<template>
  <div class="mainBox">
    <div>
      <Table stripe :columns="merchantTable.columns" :data="merchantTable.data"></Table>
    </div>

    <div>
      <Divider orientation="left">商户的收款账号信息</Divider>
      <div class="optionBox">
        <Button type="primary" @click="addMerchantAccount" size="small">添加收款账号</Button>
      </div>
      <Table stripe :columns="merchantAccountTable.columns" :data="merchantAccountTable.data"></Table>
    </div>

    <!-- 收款码数据集合 -->
    <div>
      <Drawer
            :title="merchantAccountCollectMoneyCodeTableDrawer.title"
            v-model="merchantAccountCollectMoneyCodeTableDrawer.display"
            width="720"
            :mask-closable="false"
        >
        <div style="margin-bottom: 10px;">
          <Upload
            :show-upload-list="false"
            :on-success="handleUploadSuccess"
            :format="['jpg','jpeg','png']"
            :headers="uploadCollectMoneyCodeConfig.headers"
            :data="uploadCollectMoneyCodeConfig.data"
            :name="uploadCollectMoneyCodeConfig.name"
            :max-size="2048"
            :on-exceeded-size="handleUploadExceed"
            :before-upload="handleBeforeUpload"
            multiple
            :action="uploadCollectMoneyCodeConfig.action">
            <Button icon="ios-cloud-upload-outline">上传支付宝收款码</Button>
          </Upload>
        </div>
        <Table stripe :columns="merchantAccountCollectMoneyCodeTable.columns" :data="merchantAccountCollectMoneyCodeTable.data"></Table>
      </Drawer>
    </div>
    <!-- 收款码数据集合 end-->

    <!-- 付款二维码图片 -->
    <div id="rechargePayQrCodeBox" style="display:none">
    </div>
    <!-- 付款二维码图片 end -->
    <Modal v-model="merchantRechargeConfig.display" width="400">
        <p slot="header" style="color:#19be6b;text-align:center">
            <Icon type="logo-yen" />
            <span>请使用支付宝扫码支付{{merchantRechargeConfig.amount}}元</span>
        </p>
        <div style="text-align:center">
          <div>支付完成请点击”已支付成功“</div>
          <vue-qr :text="merchantRechargeConfig.payUrl" :size="200"></vue-qr>
        </div>
        <div slot="footer">
            <Button type="success" @click="closeRechangeDialog">已支付成功</Button>
            <Button @click="merchantRechargeConfig.display = false">未支付</Button>
        </div>
    </Modal>
  </div>
</template>

<script>
import MerchantInfoApi from "@/apis/MerchantInfoManage";
import ServerResponseCode from "@/utils/ServerResponseCode";
import {fetchList, deleteById, UPLOAD_IMG_URL} from "@/apis/MerchantCollectMoneyCodeManage";
import {isBlank} from '@/utils/validate';
import { getToken, removeToken } from '@/utils/auth';
import VueQr from 'vue-qr';

export default {
  components: {
    'VueQr': VueQr,
  },
  data() {
    return {
      title: "商户信息管理",
      // 商户信息表格
      merchantTable: {
        columns: [
          { key: "code", title: "商户号", width: 80 },
          { key: "email", title: "商户邮箱", width: 180 },
          { key: "serviceChargeBalance", title: "剩余服务费(元)", width: 120 },
          { key: "serverChargeRate", title: "服务费率(元)", width: 120 },
          // { key: "phone", title: "商户手机号", width: 120 },
          // { key: "name", title: "商户名称", width: 120 },
          { key: "createTime", title: "创建时间" },
          { key: "action", title: "操作",
          render: (h, params) => {
              return h('div', [
                  h('Button', {
                      props: {
                          type: 'success',
                          size: 'small'
                      },
                      style: {
                          marginRight: '5px'
                      },
                      on: {
                        click: () =>{
                          this.openRechangeDialog();
                        }
                      }
                  }, '充值服务费'),
                  h('Button', {
                      props: {
                          type: 'success',
                          size: 'small'
                      },
                      on: {
                        click: () =>{
                          this.openUpdateLoginPasswordDialog(params.row.email);
                        }
                      }
                  }, '修改登录密码')
              ]);
          }}
        ],
        data: []
      },
      // 商户的收款账户信息表格
      merchantAccountTable: {
        columns: [
          { key: "merCode", title: "所属商户号", width: 100 },
          { key: "account", title: "收款系统账户", width: 120 },
          { key: "key", title: "秘钥", width: 260 },
          { key: "zfbAccount", title: "支付宝账户", width: 220 },
          { key: "onLine", title: "APP在线状态", width: 220,  
            render: (h, params) => {
                return h('div', [
                  this.getAccountAppOnLineStatusTag(h, params.row.onLine)
                ]);
            }
          },
          { key: "createTime", title: "创建时间", width: 160},
          { key: "id", title: "操作",
          render: (h, params) => {
              return h('div', [
                  h('Button', {
                      props: {
                          type: 'success',
                          size: 'small'
                      },
                      style: {
                          marginRight: '5px'
                      },
                      on: {
                          click: () => {
                            this.listMerchantAccountCollectMoneyCode(params.row);
                          }
                      }
                  }, '查看收款码'),
                  h('Button', {
                      props: {
                          type: 'info',
                          size: 'small'
                      },
                      style: {
                          marginRight: '5px'
                      },
                      on: {
                        click: () => {
                          this.updateMerchantAccount(params.row.account, params.row.zfbAccount);
                        }
                      }
                  }, '修改'),
                  h('Button', {
                      props: {
                          type: 'error',
                          size: 'small'
                      },
                      on: {
                        click: () => {
                          this.deleteMerchantAccount(params.row.account);
                        }
                      }
                  }, '删除')
              ]);
          }},
        ],
        data: []
      },
      // 商户的收款账户下的收款码数据信息表格
      merchantAccountCollectMoneyCodeTable: {
        columns: [
          { key: "merCode", title: "所属商户号", width: 100 },
          { key: "account", title: "收款系统账户", width: 120 },
          { key: "money", title: "收款码金额", width: 100 },
          { key: "createTime", title: "创建时间", width: 160 },
          { key: "id", 
           title: "操作",
          render: (h, params) => {
              return h('div', [
                  h('Button', {
                      props: {
                          type: 'error',
                          size: 'small'
                      },
                      on: {
                        click: () => {
                          this.deleteMerchantAccountCollectMoneyCode(params.row.id, params.index);
                        }
                      }
                  }, '删除')
              ]);
          }},
        ],
        data: []
      },
      // 收款二维码数据展示状态
      merchantAccountCollectMoneyCodeTableDrawer:{
        display: false,
        title: '',
      },
      // 添加和修改收款账户中的支付宝账号
      merchantAccountZfbAccount: '',
      // 上传的收款码配置对象
      uploadCollectMoneyCodeConfig: {
        action: UPLOAD_IMG_URL,
        name: "imgFiles",
        headers: {
          token: getToken()
        },
        data: {
          account: ''
        }
      },
      // 充值数据
      merchantRechargeConfig: {
        // 充值金额，单位元
        amount: 10.0,
        display: false,
        payUrl: ''
      },
      // 修改的密码参数
      loginNewPassword: null,
      // 定时查询app在线状态的定时器
      loadAccountAppOnLineTimer: null
    };
  },
  methods: {
    // 查询
    loadMerchantInfo() {
      MerchantInfoApi.fetchMerchant().then(response => {
        if (response.code === ServerResponseCode.SUCCESS) {
          if(this.merchantTable.data.length <= 0) {
            this.merchantTable.data.push(response.data);
          }else {
            this.merchantTable.data[0] = response.data;
          }
        } else {
          this.$Message.warning(response.msg);
        }
      });
    },
    // 查询商户下的收款账号集合
    listMerchantAccountList() {
      // 清除定时器
      clearInterval(this.loadAccountAppOnLineTimer);
      MerchantInfoApi.fetchMerchantAccountList().then(response => {
        if (response.code === ServerResponseCode.SUCCESS) {
          this.merchantAccountTable.data = response.data;
          // 开始查询app的在线状态
          this.loadAccountAppOnLine();
        } else {
          this.$Message.warning(response.msg);
        }
      });
    },
    // 添加收款账号
    addMerchantAccount() {
      this.$Modal.confirm({
          title: "请输入收款的支付宝账号",
          content: "请输入收款的支付宝账号",
          okText: "确定添加",
          onOk: () => {
              // 收款的支付宝账号不能为空
              if(isBlank(this.merchantAccountZfbAccount)){
                  this.$Message.warning("收款的支付宝账号不能为空");
                  return;
              }
              MerchantInfoApi.addMerchantAccount(this.merchantAccountZfbAccount).then(response => {
                if (response.code === ServerResponseCode.SUCCESS) {
                  // 如果成功。重新获取列表
                  this.listMerchantAccountList();
                  this.$Message.success(response.msg);
                } else {
                  this.$Message.warning(response.msg);
                }
              });
          },
          render: (h) => {
              return h('Input', {
                  props: {
                      value: this.merchantAccountZfbAccount,
                      autofocus: true,
                      placeholder: '请输入收款的支付宝账号'
                  },
                  on: {
                      input: (val) => {
                          this.merchantAccountZfbAccount = val;
                      }
                  }
              })
          }
      });
    },
    // 修改收款账号
    updateMerchantAccount(account, zfbAccount) {
      this.$Modal.confirm({
          title: "请输入收款的支付宝账号",
          content: "请输入收款的支付宝账号",
          okText: "确定修改",
          onOk: () => {
              // 收款的支付宝账号不能为空
              if(isBlank(this.merchantAccountZfbAccount)){
                  this.$Message.warning("收款的支付宝账号不能为空");
                  return;
              }
              MerchantInfoApi.updateMerchantAccount(account, this.merchantAccountZfbAccount).then(response => {
                if (response.code === ServerResponseCode.SUCCESS) {
                  // 如果成功。重新获取列表
                  this.listMerchantAccountList();
                  this.$Message.success(response.msg);
                } else {
                  this.$Message.warning(response.msg);
                }
              });
          },
          render: (h) => {
              return h('Input', {
                  props: {
                      value: zfbAccount,
                      autofocus: true,
                      placeholder: '请输入收款的支付宝账号'
                  },
                  on: {
                      input: (val) => {
                          this.merchantAccountZfbAccount = val;
                      }
                  }
              })
          }
      });
    },
    // 删除商户收款账号
    deleteMerchantAccount(account) {
      this.$Modal.confirm({
        title: "删除提示",
        content: "删除账号同时会删除旗下的所有收款码数据，是否确认删除?",
        onOk: () => {
          MerchantInfoApi.deleteMerchantAccount(account).then(response => {
            if (response.code === ServerResponseCode.SUCCESS) {
              // 如果成功。重新获取列表
              this.listMerchantAccountList();
              this.$Message.success(response.msg);
            } else {
              this.$Message.warning(response.msg);
            }
          });
        }
      });
    },
    // 根据收款商户的账号查询收款码数据集合
    listMerchantAccountCollectMoneyCode(row) {
      let title = "商户收款码账户:" + row.zfbAccount + "下的收款码数据集合";
      this.merchantAccountCollectMoneyCodeTableDrawer.title = title;
      console.log("title:" + this.merchantAccountCollectMoneyCodeTableDrawer.title);
      this.merchantAccountCollectMoneyCodeTableDrawer.display = true;
      // 设置上传的收款码的账户附加参数
      this.uploadCollectMoneyCodeConfig.data.account = row.account;
      this.merchantAccountCollectMoneyCodeTable.data = [];
      fetchList(row.account).then(response => {
          if (response.code === ServerResponseCode.SUCCESS) {
            // 如果成功。重新获取列表
            this.merchantAccountCollectMoneyCodeTable.data = response.data;
          } else {
            this.$Message.warning(response.msg);
          }
        });
    },
    // 处理上传之前
    handleBeforeUpload(obj) {
      console.log(obj);
    },
    // 处理选择的图片超过限制时提示
    handleUploadExceed(files, fileList) {
      this.$alert("每次最多上传20张收款码图片", "错误", {
        confirmButtonText: "确定",
        callback: action => {}
      });
    },
    // 处理图片上传完成后
    handleUploadSuccess(response, file, fileList) {
      if (response.code === ServerResponseCode.SUCCESS) {
        this.$Message.success("上传成功");
        fetchList(this.uploadCollectMoneyCodeConfig.data.account).then(response => {
          if (response.code === ServerResponseCode.SUCCESS) {
            // 如果成功。重新获取列表
            this.merchantAccountCollectMoneyCodeTable.data = response.data;
          } else {
            this.$Message({
              message: response.msg,
              type: "warning"
            });
          }
        });
      } else {
        this.$Message.warning(response.msg);
      }
    },
    // 根据id删除收款码
    deleteMerchantAccountCollectMoneyCode(id, index) {
      this.$Modal.confirm({
          title: '删除提示',
          content: '确定要删除此收款码吗？',
          onOk: () => {
              deleteById(id).then(response => {
                if (response.code === ServerResponseCode.SUCCESS) {
                  // 如果删除成功，则
                  this.merchantAccountCollectMoneyCodeTable.data.splice(index, 1);
                } else {
                  this.$Message.warning(response.msg);
                }
              })
          },
          onCancel: () => {
          }
      });
    },
    // 打开充值对话框
    openRechangeDialog() {
      this.$Modal.confirm({
          title: "请输入要充值的金额，单位元",
          okText: "确定",
          onOk: () => {
            if(this.merchantRechargeConfig.amount < 0.1){
                this.$Message.warning("充值金额，最低10元");
                return;
            }
            // 发起充值请求
            MerchantInfoApi.getRechargePayCode(this.merchantRechargeConfig.amount).then(response => {
              if (response.code === ServerResponseCode.SUCCESS) {
                this.merchantRechargeConfig.payUrl = response.data;
                // 展示付款二维码
                this.merchantRechargeConfig.display = true;
              } else {
                this.$Message.warning(response.msg);
              }
            });
          },
          render: (h) => {
            return h('Input', {
              props: {
                value: this.merchantRechargeConfig.amount,
                autofocus: true,
                placeholder: '请输入要充值的金额，单位元'
              },
              on: {
                  input: (val) => {
                    this.merchantRechargeConfig.amount = val;
                  }
              }
            })
          }
      });
    },
    // 处理充值成功的按钮
    closeRechangeDialog() {
      this.merchantRechargeConfig.display = false;
      this.loadMerchantInfo();
      setTimeout(()=>{
        this.loadMerchantInfo();
      }, 3000);
    },
    // 打开修改登录密码对话框
    openUpdateLoginPasswordDialog(email) {
      this.$Modal.confirm({
          title: "请输入新的登录密码",
          okText: "确定",
          onOk: () => {
            if(!this.loginNewPassword){
                this.$Message.warning("新的密码不能为空");
                return;
            }
            // 发起充值请求
            MerchantInfoApi.updateLoginPassword(this.loginNewPassword, email).then(response => {
              if (response.code === ServerResponseCode.SUCCESS) {
                this.$Message.success(response.msg);
                setTimeout(() => {
                  // 删除token
                  removeToken();
                  // 跳转到登录页面
                  this.$router.push({path: '/login'});
                }, 1500);
              } else {
                this.$Message.warning(response.msg);
              }
            });
          },
          render: (h) => {
            return h('Input', {
              props: {
                value: this.loginNewPassword,
                autofocus: true,
                placeholder: '请输入新的登录密码'
              },
              on: {
                  input: (val) => {
                    this.loginNewPassword = val;
                  }
              }
            })
          }
      });
    },
    // 获取app在线状态的标签
    getAccountAppOnLineStatusTag(h, status) {
      let statusMsg = '不在线';
      let _type = 'default';
      switch(status) {
        case 0:
          statusMsg = "在线-异常";
          _type = 'warning';
          break;
        case 1:
          statusMsg = "在线-正常";
          _type = 'success';
          break;
      }
      return h('Tag', {
                props: {
                    color: _type,
                    size: 'small'
                }
              }, statusMsg);
    },
    // 定时1分钟检查app在线状态
    loadAccountAppOnLine() {
      for(let i=0; i<this.merchantAccountTable.data.length; i++) {
        let merchantAccount = this.merchantAccountTable.data[i];
        MerchantInfoApi.loadAccountAppOnLine(merchantAccount.account).then(response => {
          if (response.code === ServerResponseCode.SUCCESS) {
            this.merchantAccountTable.data[i].onLine = response.data;
          } else {
            this.merchantAccountTable.data[i].onLine = -1;
          }
        });
      }
    },
    // 创建定时器
    makeLoadAccountAppOnLineTimer() {
      let vueThis = this;
      this.loadAccountAppOnLineTimer = setInterval(() =>{
        vueThis.loadAccountAppOnLine();
      }, 1000 * 60 * 1);
    }
  },
  // 组件挂载时执行
  mounted() {
    this.loadMerchantInfo();
    this.listMerchantAccountList();
    // 创建定时器进行查询
    this.makeLoadAccountAppOnLineTimer();
  },
  // 路由切换时，执行
  beforeRouteLeave (to, from, next) {
    // 清除定时器
    clearInterval(this.loadAccountAppOnLineTimer);
    // 调用next调整到下一个路由
    next();
  }
};
</script >

<style scoped>
/* 复写表格表头样式 */
#merchantTable.el-table .table-head-th {
  background: red !important;
}
.mainBox {
  padding: 0 10px;
}

.Divider {
  margin: 5px 0;
}
.optionBox {
  margin: 5px;
}
</style>


